﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Genuilder.Extensibility;
using System.Reflection;
using System.Runtime.Serialization;

namespace Genuilder.Extensions
{
	[DataContract]
	public class EmbeddedResourceExtension : IExtension
	{
		public EmbeddedResourceExtension()
		{
			ClassName = "EmbeddedResources";
		}
		[DataMember]
		public string Namespace
		{
			get;
			set;
		}

		[DataMember]
		public string ClassName
		{
			get;
			set;
		}

		#region IExtension Members

		public void Execute(ExtensionContext extensionContext)
		{
			var embeddedResources = extensionContext.GenItems.Where(s => s.SourceType == SourceType.EmbeddedResource).ToList();
			if(embeddedResources.Any(e => e.Modified))
			{
				var result = new EmbeddedResource.EmbeddedResourceClass()
				{
					ClassName = ClassName,
					Namespace = Namespace == null ? extensionContext.ExecutionContext.ProjectInfo.RootNamespace : Namespace,
					EmbeddedResources = embeddedResources
										.Select(s => new EmbeddedResource.EmbeddedResource(GetResourceName(s.Name, extensionContext)))
										.ToList()
				}.TransformText();
				extensionContext.GenItems.CreateNew("EmbeddedResources.g.cs").WriteAllText(result);
			}
		}

		private string GetResourceName(string file, ExtensionContext extension)
		{
			var ns = extension.ExecutionContext.ProjectInfo.RootNamespace;
			if(file.StartsWith(".."))
				return ns + "." + GetLastPart(file);
			List<string> parts = new List<string>();
			parts.Add(ns);
			parts.AddRange(file.Split('/', '\\'));
			return String.Join(".", parts.ToArray());
		}

		private string GetLastPart(string file)
		{
			return file.Split('/', '\\').Last();
		}

		#endregion
	}
}
